package com.ht.aems.ucp;

import com.ht.aems.util.ObjectBuffer;
import com.ht.log.CommandPersistLayer;
import com.ht.log.DeviceCommand;
import com.ht.log.MPLFactory;
import org.apache.log4j.Logger;

/**
 * Created by IntelliJ IDEA.
 *
 * @author Dong Shufeng
 *         Date: 2010-3-11
 */
public class CommandSaver {
    private static Logger log = Logger.getLogger(CommandSaver.class);

    private static ObjectBuffer buffer = new ObjectBuffer(500);

    static {
        Thread thread = new Thread() {
            public void run() {
                while (true) {
                    try {
                        Object[] cmds = buffer.read();
                        if (cmds != null && cmds.length > 0) {
                            CommandPersistLayer cmdPersistLayer = MPLFactory.createCmdPersist();
                            log.info("Saving command start... command length: " + cmds.length);
                            for (Object obj : cmds) {
                                DeviceCommand command = (DeviceCommand) obj;
                                cmdPersistLayer.addCommand(command);
                            }
                            cmdPersistLayer.close();
                            log.info("Saving command end.");
                        }
                        sleep(5000l);
                    } catch (Exception e) {
                        log.warn("Exception when saving message to db: " + e);
                    }
                }
            }
        };
        thread.start();
    }

    public static void saveCommand(DeviceCommand c) {
        buffer.write(new Object[]{c});
    }
}
